package com.itboye.mengwu.app.ui.aiwujia;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;
import java.util.Observable;
import java.util.Observer;

import com.itboye.config.GlobalConfig;
import com.itboye.core.object.BaseActivity;
import com.itboye.core.object.ResultEntity;
import com.itboye.core.object.SpPublicParams;
import com.itboye.core.utils.MyRunnable;
import com.itboye.core.utils.SPUtils;
import com.itboye.core.utils.XImageLoader;
import com.itboye.inageview.RoundImageView;
import com.itboye.mengwu.R;
import com.itboye.mengwu.address.CityModel;
import com.itboye.mengwu.address.ProvinceModel;
import com.itboye.mengwu.app.ui.aiwujia.ActivityZengWuXianZengSongFang.LvShenQingJiLuAdapter;
import com.itboye.mengwu.app.ui.aizhiwu.GeRenActivity;
import com.itboye.mengwu.app.ui.main.PingLunBaoBeiActivity;
import com.itboye.mengwu.data.model.NewMaMaZengXiangQing;
import com.itboye.mengwu.data.presenter.NewMaMaZengPresenter;
import com.itboye.mengwu.luntan.comment.view.MyListView;

import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.StrictMode;
import android.text.TextUtils;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.ScrollView;
import android.widget.TextView;

public class ActivityZengWuXianShouZengFang extends BaseActivity implements
		Observer {

	MyListView lvShenQingJiLu;
	ImageView imgBack, shoucangIv;

	NewMaMaZengPresenter newMaMaZengPresenter;
	String uid, pid;
	NewMaMaZengXiangQing newMaMaZengXiangQing;

	TextView nickname, detail, createtime_show, tvAddress, winNickName,
			winTime, shoucangTv;
	RoundImageView head, winHead;
	LinearLayout winLine;
	RelativeLayout shoucangLine, qurenshouhuoLine;
	RelativeLayout nodata;
	TextView nodata_tv;
	LinearLayout imagesLine;
	DisplayMetrics displayMetrics = new DisplayMetrics();

	// 数据库
	private SQLiteDatabase db;

	List<ProvinceModel> provinceLv = new ArrayList<ProvinceModel>();
	List<CityModel> cityLv = new ArrayList<CityModel>();
	private String DB_PATH;// =App.ctx.getCacheDir().getCanonicalPath() +
							// "/address";
	private final String DB_FILENAME = "itboye.db";

	String provinceName, cityName;

	@Override
	public int initView() {

		return R.layout.activity_zengwuxian_shouzengfang;
	}

	@Override
	public void onMyCreate() {
		StrictMode.setThreadPolicy(new StrictMode.ThreadPolicy.Builder()
				.detectDiskReads().detectDiskWrites().detectNetwork()
				.penaltyLog().build());

		StrictMode.setVmPolicy(new StrictMode.VmPolicy.Builder()
				.detectLeakedSqlLiteObjects().penaltyLog().penaltyDeath()
				.build());
		lvShenQingJiLu = (MyListView) findViewById(R.id.lvShenQingJiLu);
		head = (RoundImageView) findViewById(R.id.head);
		winHead = (RoundImageView) findViewById(R.id.winHead);
		Intent intent = getIntent();

		uid = SPUtils.get(this, null, SpPublicParams.UID, "") + "";
		pid = intent.getStringExtra("pid");
		newMaMaZengPresenter = new NewMaMaZengPresenter(this);
		newMaMaZengPresenter.xiangqing(pid, uid, "10");

		imgBack.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				finish();

			}
		});
		shoucangLine.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				if ("收藏".equals(shoucangTv.getText())) {
					newMaMaZengPresenter.shoucang(pid, uid, "1", "3");

				} else if ("已收藏".equals(shoucangTv.getText())) {
					newMaMaZengPresenter.shoucang(pid, uid, "0", "3");

				}

			}
		});
		qurenshouhuoLine.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				Intent intent = new Intent(ActivityZengWuXianShouZengFang.this,
						ActivityMaMaZengPingLunBaoBei.class);
				intent.putExtra("pid", pid);
				startActivity(intent);
				finish();

			}
		});

	}

	private void initMyView(NewMaMaZengXiangQing newMaMaZengXiangQing) {
		StrictMode.setThreadPolicy(new StrictMode.ThreadPolicy.Builder()
				.detectDiskReads().detectDiskWrites().detectNetwork()
				.penaltyLog().build());
		StrictMode.setVmPolicy(new StrictMode.VmPolicy.Builder()
				.detectLeakedSqlLiteObjects().detectLeakedClosableObjects()
				.penaltyLog().penaltyDeath().build());

		getWindowManager().getDefaultDisplay().getMetrics(displayMetrics);
		int screenWidth = getWindowManager().getDefaultDisplay().getWidth();

		if (newMaMaZengXiangQing.getShowImgs() != null
				&& newMaMaZengXiangQing.getShowImgs().size() > 0) {
			Log.e(".....", newMaMaZengXiangQing.getShowImgs().size() + "");
			new MyRunnable(this,
					(ArrayList<String>) newMaMaZengXiangQing.getShowImgs(),
					null, newMaMaZengXiangQing.getShowImgs().size(),
					screenWidth, displayMetrics, imagesLine);

		}
		// // 给第一个listView加手写的高度，让他不能滑动！，然后赋对应的adapter
		// int totalLvImagesHeight = 0;
		// LvImagesAdapter lvImagesAdapter = new LvImagesAdapter(this,
		// newMaMaZengXiangQing);
		// for (int i = 0; i < lvImagesAdapter.getCount(); i++) {
		// View listItem = lvImagesAdapter.getView(i, null, lvImages);
		// listItem.measure(0, 0);
		// totalLvImagesHeight += listItem.getMeasuredHeight();
		// }
		// ViewGroup.LayoutParams params = lvImages.getLayoutParams();
		// params.height = totalLvImagesHeight + (lvImages.getDividerHeight() *
		// (lvImagesAdapter.getCount() - 1));
		// lvImages.setLayoutParams(params);
		// lvImages.setAdapter(lvImagesAdapter);

		// 给第二个listView加手写的高度，让他不能滑动！，然后赋对应的adapter
		int totalLvShenQingJiLuHeight = 0;
		LvShenQingJiLuAdapter lvShenQingJiLuAdapter = new LvShenQingJiLuAdapter(
				this, newMaMaZengXiangQing);
		lvShenQingJiLu.setDividerHeight(0);
		for (int i = 0; i < lvShenQingJiLuAdapter.getCount(); i++) {
			View listItem1 = lvShenQingJiLuAdapter.getView(i, null,
					lvShenQingJiLu);
			listItem1.measure(0, 0);
			totalLvShenQingJiLuHeight += listItem1.getMeasuredHeight();
		}
		ViewGroup.LayoutParams params1 = lvShenQingJiLu.getLayoutParams();
		params1.height = totalLvShenQingJiLuHeight;
		lvShenQingJiLu.setLayoutParams(params1);
		lvShenQingJiLu.setAdapter(lvShenQingJiLuAdapter);
		if (newMaMaZengXiangQing.getapplyList().getList().size() == 0) {
			nodata.setVisibility(View.VISIBLE);
			nodata_tv.setText("还没人申请，赶快来申请吧~");
			lvShenQingJiLu.setVisibility(View.GONE);
		} else {
			nodata.setVisibility(View.GONE);
			lvShenQingJiLu.setVisibility(View.VISIBLE);
		}
		((ScrollView) findViewById(R.id.scrollview)).smoothScrollTo(0, 0);

	}

	public class LvImagesAdapter extends BaseAdapter {
		private LayoutInflater mInflater = null;
		NewMaMaZengXiangQing newMaMaZengXiangQing;

		private LvImagesAdapter(Context context,
				NewMaMaZengXiangQing newMaMaZengXiangQing) {
			// 根据context上下文加载布局，这里的是Demo17Activity本身，即this
			this.mInflater = LayoutInflater.from(context);
			this.newMaMaZengXiangQing = newMaMaZengXiangQing;
		}

		@Override
		public int getCount() {
			// How many items are in the data set represented by this Adapter.
			// 在此适配器中所代表的数据集中的条目数
			return newMaMaZengXiangQing != null ? newMaMaZengXiangQing
					.getShowImgs().size() : 0;
		}

		@Override
		public Object getItem(int position) {
			// Get the data item associated with the specified position in the
			// data set.
			// 获取数据集中与指定索引对应的数据项
			return newMaMaZengXiangQing.getShowImgs().get(position);
		}

		@Override
		public long getItemId(int position) {
			// Get the row id associated with the specified position in the
			// list.
			// 获取在列表中与指定索引对应的行id
			return position;
		}

		// Get a View that displays the data at the specified position in the
		// data set.
		// 获取一个在数据集中指定索引的视图来显示数据
		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			ViewHolder holder = null;
			// 如果缓存convertView为空，则需要创建View
			if (convertView == null) {
				holder = new ViewHolder();
				// 根据自定义的Item布局加载布局
				convertView = mInflater.inflate(
						R.layout.item_zengwuxian_youke_img, null);
				holder.img = (ImageView) convertView.findViewById(R.id.iv);
				// 将设置好的布局保存到缓存中，并将其设置在Tag里，以便后面方便取出Tag
				convertView.setTag(holder);
			} else {
				holder = (ViewHolder) convertView.getTag();
			}
			// holder.img.setBackgroundResource((Integer)
			// data.get(position).get("img"));
			if (newMaMaZengXiangQing.getShowImgs().get(position) != null) {
				XImageLoader.load(GlobalConfig.API_URL + "/picture/index?id="
						+ newMaMaZengXiangQing.getShowImgs().get(position),
						holder.img);
			}
			return convertView;
		}

		class ViewHolder {
			public ImageView img;

		}

	}

	public class LvShenQingJiLuAdapter extends BaseAdapter {
		private LayoutInflater mInflater = null;
		NewMaMaZengXiangQing newMaMaZengXiangQing;

		private LvShenQingJiLuAdapter(Context context,
				NewMaMaZengXiangQing newMaMaZengXiangQing) {
			// 根据context上下文加载布局，这里的是Demo17Activity本身，即this
			this.mInflater = LayoutInflater.from(context);
			this.newMaMaZengXiangQing = newMaMaZengXiangQing;
		}

		@Override
		public int getCount() {
			// How many items are in the data set represented by this Adapter.
			// 在此适配器中所代表的数据集中的条目数
			return newMaMaZengXiangQing.getapplyList().getList().size() > 0 ? newMaMaZengXiangQing
					.getapplyList().getList().size()
					: 0;
		}

		@Override
		public Object getItem(int position) {
			// Get the data item associated with the specified position in the
			// data set.
			// 获取数据集中与指定索引对应的数据项
			return newMaMaZengXiangQing.getapplyList().getList().get(position);
		}

		@Override
		public long getItemId(int position) {
			// Get the row id associated with the specified position in the
			// list.
			// 获取在列表中与指定索引对应的行id
			return position;
		}

		// Get a View that displays the data at the specified position in the
		// data set.
		// 获取一个在数据集中指定索引的视图来显示数据
		@Override
		public View getView(final int position, View convertView,
				ViewGroup parent) {
			ViewHolder holder = null;
			// 如果缓存convertView为空，则需要创建View
			if (convertView == null) {
				holder = new ViewHolder();
				// 根据自定义的Item布局加载布局
				convertView = mInflater.inflate(
						R.layout.item_zengwuxian_shenqingjilu, null);

				holder.applyTime = (TextView) convertView
						.findViewById(R.id.applyTime);
				holder.head = (RoundImageView) convertView
						.findViewById(R.id.head);
				holder.nickName = (TextView) convertView
						.findViewById(R.id.nickName);
				holder.reason = (TextView) convertView
						.findViewById(R.id.reason);
				// holder.img = (ImageView) convertView.findViewById(R.id.iv);
				// 将设置好的布局保存到缓存中，并将其设置在Tag里，以便后面方便取出Tag
				holder.zengsong = (TextView) convertView
						.findViewById(R.id.zengsong);
				convertView.setTag(holder);
			} else {
				holder = (ViewHolder) convertView.getTag();
			}
			// holder.img.setBackgroundResource((Integer)
			// data.get(position).get("img"));
			holder.applyTime.setText(newMaMaZengXiangQing.getapplyList()
					.getList().get(position).getapplyTimeShow());
			holder.nickName.setText(newMaMaZengXiangQing.getapplyList()
					.getList().get(position).getNickname());
			holder.reason.setText(newMaMaZengXiangQing.getapplyList().getList()
					.get(position).getReason());
			if (TextUtils.isEmpty(newMaMaZengXiangQing.getSendInfo().getUid())) {
				holder.zengsong.setVisibility(View.VISIBLE);
			}
			// if
			// (newMaMaZengXiangQing.getapplyList().getList().get(position).getHead()
			// != null) {
			// XImageLoader.load(GlobalConfig.API_URL + "/picture/index?id="
			// +
			// newMaMaZengXiangQing.getapplyList().getList().get(position).getHead(),
			// holder.head);
			// }
			if (newMaMaZengXiangQing.getapplyList().getList().get(position)
					.getHead() == null
					|| "".equals(newMaMaZengXiangQing.getapplyList().getList()
							.get(position).getHead())) {
				if ("1".equals(newMaMaZengXiangQing.getapplyList().getList()
						.get(position).getSex())) {
					holder.head.setImageResource(R.drawable.male);
				} else {
					holder.head.setImageResource(R.drawable.female);
				}

			} else {
				if (newMaMaZengXiangQing.getapplyList().getList().get(position)
						.getHead().startsWith("http")) {
					XImageLoader.load(newMaMaZengXiangQing.getapplyList()
							.getList().get(position).getHead(), holder.head);
				} else {
					XImageLoader.load(GlobalConfig.API_URL
							+ "/picture/index?id="
							+ newMaMaZengXiangQing.getapplyList().getList()
									.get(position).getHead(), holder.head);
				}

			}
			holder.zengsong.setOnClickListener(new OnClickListener() {

				@Override
				public void onClick(View v) {

					newMaMaZengPresenter.zengsongxuanze(
							pid,
							newMaMaZengXiangQing.getapplyList().getList()
									.get(position).getId(), uid);

				}
			});

			holder.head.setOnClickListener(new OnClickListener() {

				@Override
				public void onClick(View v) {
					// TODO Auto-generated method stub
					Intent intent = new Intent(
							ActivityZengWuXianShouZengFang.this,
							GeRenActivity.class);
					intent.putExtra("uid", uid);
					intent.putExtra("fromUid", newMaMaZengXiangQing
							.getapplyList().getList().get(position).getUid()
							+ "");
					startActivity(intent);
				}
			});
			return convertView;
		}

		class ViewHolder {
			// public ImageView img;
			public RoundImageView head;
			public TextView nickName, reason, applyTime, zengsong;

		}

	}

	@Override
	public void update(Observable observable, Object data) {
		ResultEntity entity = super.handlerError(data);
		if (entity != null) {
			if (entity.getEventType() == NewMaMaZengPresenter.XiangqingSuccess) {

				newMaMaZengXiangQing = (NewMaMaZengXiangQing) entity.getData();

				nickname.setText(newMaMaZengXiangQing.getNickname());
				detail.setText(newMaMaZengXiangQing.getDetail());
				createtime_show.setText(newMaMaZengXiangQing
						.getCreatetimeShow());
				getProviceName(newMaMaZengXiangQing.getLocProvince(),
						newMaMaZengXiangQing.getLocCity());
				tvAddress.setText(provinceName + cityName);

				// XImageLoader.load(GlobalConfig.API_URL + "/picture/index?id="
				// + newMaMaZengXiangQing.getHead(), head);
				if (newMaMaZengXiangQing.getHead() == null
						|| "".equals(newMaMaZengXiangQing.getHead())) {
					if ("1".equals(newMaMaZengXiangQing.getSex())) {
						head.setImageResource(R.drawable.male);
					} else {
						head.setImageResource(R.drawable.female);
					}

				} else {
					if (newMaMaZengXiangQing.getHead().startsWith("http")) {
						XImageLoader.load(newMaMaZengXiangQing.getHead(), head);
					} else {
						XImageLoader.load(
								GlobalConfig.API_URL + "/picture/index?id="
										+ newMaMaZengXiangQing.getHead(), head);
					}

				}
				Log.e("newMaMaZengXiangQing.getHead()",
						newMaMaZengXiangQing.getHead());
				winNickName.setText(newMaMaZengXiangQing.getSendInfo()
						.getNickname());
				SimpleDateFormat myFmt = new SimpleDateFormat(
						"yyyy年MM月dd日 HH时mm分");
				winTime.setText(myFmt.format(Long
						.parseLong(newMaMaZengXiangQing.getSendInfo()
								.getWinTime()) * 1000));
				// XImageLoader.load(
				// GlobalConfig.API_URL + "/picture/index?id=" +
				// newMaMaZengXiangQing.getSendInfo().getHead(),
				// winHead);
				if (newMaMaZengXiangQing.getSendInfo().getHead() == null
						|| "".equals(newMaMaZengXiangQing.getSendInfo()
								.getHead())) {
					if ("1".equals(newMaMaZengXiangQing.getSendInfo().getSex())) {
						winHead.setImageResource(R.drawable.male);
					} else {
						winHead.setImageResource(R.drawable.female);
					}

				} else {
					if (newMaMaZengXiangQing.getSendInfo().getHead()
							.startsWith("http")) {
						XImageLoader.load(newMaMaZengXiangQing.getSendInfo()
								.getHead(), winHead);
					} else {
						XImageLoader.load(GlobalConfig.API_URL
								+ "/picture/index?id="
								+ newMaMaZengXiangQing.getSendInfo().getHead(),
								winHead);
					}

				}
				head.setOnClickListener(new OnClickListener() {

					@Override
					public void onClick(View v) {

						Intent intent = new Intent(
								ActivityZengWuXianShouZengFang.this,
								GeRenActivity.class);
						intent.putExtra("uid", uid);
						intent.putExtra("fromUid",
								newMaMaZengXiangQing.getUid() + "");
						startActivity(intent);
					}
				});
				winHead.setOnClickListener(new OnClickListener() {

					@Override
					public void onClick(View v) {

						Intent intent = new Intent(
								ActivityZengWuXianShouZengFang.this,
								GeRenActivity.class);
						intent.putExtra("uid", uid);
						intent.putExtra("fromUid", newMaMaZengXiangQing
								.getSendInfo().getUid() + "");
						startActivity(intent);
					}
				});
				if ("0".equals(newMaMaZengXiangQing.getIsFav())) {
					shoucangTv.setText("收藏");
				} else if ("1".equals(newMaMaZengXiangQing.getIsFav())) {
					shoucangTv.setText("已收藏");
				}

				if ("0".equals(newMaMaZengXiangQing.getSendInfo()
						.getEvaluateTime())) {
					qurenshouhuoLine.setBackground(getResources().getDrawable(
							R.color.main_color));
					qurenshouhuoLine.setEnabled(true);
				} else {
					qurenshouhuoLine.setBackground(getResources().getDrawable(
							R.color.mygray));
					qurenshouhuoLine.setEnabled(false);
				}

				initMyView(newMaMaZengXiangQing);

			}

			if (entity.getEventType() == NewMaMaZengPresenter.ShoucangSuccess) {
				if (shoucangIv.isSelected()) {
					shoucangTv.setText("收藏");
					shoucangIv.setSelected(false);

				} else {
					shoucangTv.setText("已收藏");
					shoucangIv.setSelected(true);

				}

			} else if (entity.getEventType() == NewMaMaZengPresenter.ShoucangFail) {

			}

		}
	}

	public void getProviceName(String provinceNo, String cityNo) {

		try {
			DB_PATH = this.getCacheDir().getCanonicalPath() + "/address";
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();

		}
		db = openDataBase();

		Cursor cursorCity = db.rawQuery("select * from common_city", null);
		while (cursorCity.moveToNext()) {
			CityModel cityModel = new CityModel(cursorCity.getString(2),
					cursorCity.getInt(1), cursorCity.getInt(3));
			cityLv.add(cityModel);
		}
		Log.e("---!1", cityNo);
		for (int i = 0; i < cityLv.size(); i++) {

			if (cityNo.equals(cityLv.get(i).getNumber() + "")) {
				cityName = cityLv.get(i).getName() + "";
				Log.e("---1", cityNo);
				Log.e("---2", cityLv.get(i).getNumber() + "");
				Log.e("---3", cityName);
			}
		}
		cursorCity.close();

		Cursor cursor = db.rawQuery("select * from common_province", null);
		while (cursor.moveToNext()) {
			ProvinceModel province1 = new ProvinceModel(cursor.getString(2),
					cursor.getInt(1));
			provinceLv.add(province1);
		}

		// mProvinceDatas = new String[provinceLv.size()];
		for (int i = 0; i < provinceLv.size(); i++) {

			if (provinceNo.equals(provinceLv.get(i).getNumber() + "")) {
				provinceName = provinceLv.get(i).getName();
			}
		}
		cursor.close();

		db.close();

	}

	private SQLiteDatabase openDataBase() {
		try {
			String dbFileName = DB_PATH + "/" + DB_FILENAME;
			File dir = new File(DB_PATH);
			if (!dir.exists()) {
				dir.mkdirs();
			}
			if (!new File(DB_PATH, DB_FILENAME).exists()) {
				new File(DB_PATH, DB_FILENAME).createNewFile();
				InputStream is = getResources().openRawResource(R.raw.itboye);
				FileOutputStream fos = new FileOutputStream(dbFileName);
				byte[] buffer = new byte[8192];
				int count = 0;
				while ((count = is.read(buffer)) > 0) {
					fos.write(buffer, 0, count);
				}
				fos.close();
				is.close();
			}
			db = SQLiteDatabase.openOrCreateDatabase(dbFileName, null);
			return db;
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}

}
